<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_BillCode_FormItem"
								prop="Entity.BillCode"
								:rules="[{ required: true, message: '单据编号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据的唯一编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" disabled clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								:auth="true"
								:rules="[{ required: true, message: '公司为必填项', trigger: 'blur' }]"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" label="所属部门" :org-id="stateData.vmModel.Entity.OrgId" :auth="true" />
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>物料信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_MaterialId_FormItem"
								prop="Entity.MaterialId"
								:rules="[{ required: true, message: '物料为必填项', trigger: 'change' }]"
							>
								<template #label>
									<WtmLabelTooltip label="物料" tooltip="关联的物料实体" />
								</template>
								<WtmMaterialSelector
									v-model="stateData.vmModel.Entity.MaterialId"
									placeholder="请选择物料"
									returnResultFields="Material"
									:allowDirectSelect="true"
									@material-select="handleMaterialSelect"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_ChangeReason_FormItem"
								prop="Entity.ChangeReason"
								:rules="[{ required: true, message: '变更原因为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="变更原因" tooltip="物料变更的原因" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ChangeReason" type="textarea" :rows="3" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysMaterialChangeRequestBillApi as api } from '/@/views/supplychain/sysmaterialchangerequestbill/api';
import other from '/@/utils/other';
import { ISysMaterialChangeRequestBillVm } from '/@/views/supplychain/sysmaterialchangerequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { commonApi } from '/@/api/common';

const BILL_STATUS = {
	DRAFT: '草稿',
	IN_AUDIT: '审核中',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const stateData = reactive<IViewModel<ISysMaterialChangeRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			MaterialId: null,
			Material: null,
			ChangeReason: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			Group: null,
			OrgId: null,
			Org: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		},

		ActionName: null,
		IsMyApprove: null,
	},
	AllSysGroups: [],
	AllSysOrgs: [],
});

/** 选中的物料信息 */
const selectedMaterial = ref<any>(null);

const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const canSubmit = computed(() => stateData.vmModel.Entity.BillStatus === BILL_STATUS.DRAFT);
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

const handleApiResponse = (response: any, isSubmit = false) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};
// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		false
	);
};

// 提交
const onSubmit = () => {
	if (!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING) {
		stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
	}
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		true
	);
};

/**
 * 处理物料选择
 * @param material - 选中的物料信息
 */
const handleMaterialSelect = (material: any) => {
	selectedMaterial.value = material;
	console.log('选中的物料:', material);
};

const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then((res) => handleApiResponse(res, true))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => {
				other.setValue(stateData.vmModel, x);
			}),
	]);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'success',
			onClick: () => handleApproval(ACTIONS.AGREE),
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: () => handleApproval(ACTIONS.REJECT),
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
